import axios from "axios";
import {ElMessage} from "element-plus";
import { TokenUtil } from '@/utils/common.js'
// 定义响应数据的接口
const ResultCode = {
    SUCCESS: 200,
    UNAUTHORIZED: 401,
    FORBIDDEN: 403,
    CREATE: 201
    // ... 可以添加更多状态码
}

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 1000 * 5,
    // 添加通用请求头
    headers: {
        'Content-Type': 'application/json'
    }
}) 

// 请求拦截器增强
service.interceptors.request.use((config) => {
    if (TokenUtil.hasToken()) {
        config.headers.Authorization = `${TokenUtil.getToken()}`
    }
    // else {
    //     // 可以统一处理未登录状态
    //     ElMessage.warning('请先登录')
    //     return Promise.reject(new Error('未登录'))
    // }
    return config
}, error => {
    ElMessage.error('请求发送失败')
    return Promise.reject(error)
})

// 响应拦截器增强
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 200 || res.code === 0 || !res.code) {
            if (res.data === 0) {
                return res.data
            }else {
                return res.data || res
            }
        } else{
            switch (res.code) {
                case ResultCode.CREATE:
                    return res.data || res
                case ResultCode.UNAUTHORIZED:
                    // 处理未授权
                    ElMessage.error('登录已过期，请重新登录')
                    // 可以在这里处理登出逻辑
                    break
                case ResultCode.FORBIDDEN:
                    ElMessage.error('没有权限访问')
                    break
                case -1:
                    ElMessage.error(res.msg || '未知错误')
                    break;
                default:
                    ElMessage.error(res.msg || '未知错误')
            }
            return Promise.reject(res.msg || '未知错误')
        }
    },
    error => {
        // ElMessage.error(error.msg || '请求失败')
        return Promise.reject(error)
    }
)

/**
 * 统一 HTTP 请求方法
 * @param {string} method - 请求方法
 * @param {string} url - 请求地址
 * @param {object} data - 请求数据
 * @param {object} config - 额外配置
 */
function request(method, url, data = {}, config = {}) {
    const options = {
        url,
        method,
        ...config
    }

    if (['post', 'put', 'patch', 'delete'].includes(method.toLowerCase())) {
        options.data = data
    } else {
        options.params = data
    }

    return service(options)
}

// 导出各种请求方法
export const http = {
    get: (url, params = {}, config = {}) => request('get', url, params, config),
    post: (url, data = {}, config = {}) => request('post', url, data, config),
    put: (url, data = {}, config = {}) => request('put', url, data, config),
    delete: (url, params = {}, config = {}) => request('delete', url, params, config),
    patch: (url, data = {}, config = {}) => request('patch', url, data, config)
}
